package com.muqi.app.qlearn.mine;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import nl.qbusict.cupboard.Cupboard;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.loopj.android.http.BaseJsonHttpResponseHandler;

import com.muqi.app.network.http.AsyncCacheHttpForGet;
import com.muqi.app.network.http.AsyncCacheHttpForGet.LoadOverListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;

import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.pj.shops.MineOrderAdapter.onPayDeleteListener;
import com.muqi.app.project.application.ActivitiesManager;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.adapter.MessageAdapter;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.ClassRoomCommentStatisticsActivity;
import com.muqi.app.qlearn.student.ui.ResolveActivity;
import com.muqi.app.qlearn.ui.MyHomeWkDetailsActivity;
import com.muqi.app.qlearn.ui.NoticeDetailsActivity;
import com.muqi.app.qlearn.ui.SystemNoticeActivity;

import com.muqi.app.user.db.CmdLoaclMessage;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;
import com.muqi.app.widget.pulltorefresh.XListView;

import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class MineMessageActivity extends BaseFragmentActivity implements
		XListView.IXListViewListener {
	private XListView mListview;
	private int limit = 20;
	private int offSet = 1;
	private int page = 0;
	private List<CmdLoaclMessage> dataList;
	private MessageAdapter mAdapter;

	private RefreshReceiver receiver;

	private CupboardSQLiteOpenHelper dbHelper;
	private SQLiteDatabase sqlDb;

	private int currentPosition = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dbHelper = new CupboardSQLiteOpenHelper(this);
		sqlDb = dbHelper.getWritableDatabase();
		setContentView(R.layout.aty_mine_message);

		IntentFilter intentFilter = new IntentFilter();
		receiver = new RefreshReceiver();
		intentFilter.addAction("message");
		registerReceiver(receiver, intentFilter); // 注册监听
	}

	@Override
	protected void onInit() {
		mListview = (XListView) findViewById(R.id.listview);
		mListview.setXListViewListener(this);
		mListview.setPullRefreshEnable(false);
		mListview.setPullLoadEnable(false);
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (dataList != null) {
					Intent intent = null;
					currentPosition = arg2 - 1;
					CmdLoaclMessage message = dataList.get(arg2 - 1);
					// Log.e("===", message.type+"type");
					switch (message.type) {
					case 1:
						intent = new Intent(mContext,
								MyHomeWkDetailsActivity.class);
						intent.putExtra(MyHomeWkDetailsActivity.HOMEWORK_ID,
								message.msg_id);
						startActivityForResult(intent, 1003);
						break;
					case 2:
						intent = new Intent(mContext,
								NoticeDetailsActivity.class);
						intent.putExtra(NoticeDetailsActivity.NOTICE_MSG_ID,
								message.msg_id);
						startActivityForResult(intent, 1003);
						break;
					case 3:
						startActivity(ClassRoomCommentStatisticsActivity.class);
						break;
					case 4:
						intent = new Intent(mContext,
								ResolveActivity.class);
						intent.putExtra("id",
								message.msg_id);
						startActivityForResult(intent, 1003);
						break;
					default:
						break;
					}
				}

			}
		});
		mListview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				final String selectedId = dataList.get(arg2 - 1).user_id;

				new SweetAlertDialog(mContext, SweetAlertDialog.NORMAL_TYPE)
						.setTitleText("确定删除该消息？").setCancelText("取消")
						.setConfirmText("确定").showCancelButton(true)
						.setCancelClickListener(new OnSweetClickListener() {
							@Override
							public void onClick(SweetAlertDialog mDialog) {
								mDialog.dismissWithAnimation();

							}
						}).setConfirmClickListener(new OnSweetClickListener() {
							@Override
							public void onClick(SweetAlertDialog mDialog) {
								mDialog.dismissWithAnimation();

								boolean f = cupboard().withDatabase(sqlDb)
										.delete(CmdLoaclMessage.class,
												dataList.get(arg2 - 1)._id);
								if (f) {
									showToast("删除成功");
									loadingData();
								}

							}

						}).show();
				return true;
			}
		});
	}

	@Override
	protected void onData() {
		loadingData();
	}

	private void loadingData() {

		dataList = cupboard().withDatabase(sqlDb).query(CmdLoaclMessage.class)
				.withSelection("user_id=?", mSpUtil.getUserId())

				.list();
		if (dataList != null) {
			if (dataList.size() <= 0) {
				showEmpty("无消息");
			} else {
				hidEmpty();
				loadView();
				if (dataList != null) {
					Collections.reverse(dataList);
					if (mAdapter != null)
						mAdapter = null;
					mAdapter = new MessageAdapter(mContext, dataList);
					mListview.setAdapter(mAdapter);
				}
			}
		}else{
			showEmpty("无消息");
		}

	}

	@Override
	public void onRefresh() {
		offSet = 1;
		loadingData();
	}

	private void loadView() {
		mListview.stopLoadMore();
		mListview.stopRefresh();
	}

	@Override
	public void onLoadMore() {
		offSet = offSet + limit * (page++);
		loadingData();
	}

	public void finish(View view) {
		finish();
	}

	private class RefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action != null && action.equals("Back_Goods")) {

			}
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		// Log.e("===",arg0+" ==="+arg1+"==== "+currentPosition);
		if (arg0 == 1003 && arg1 == RESULT_OK && currentPosition != -1
				&& arg2 != null) {
			boolean isDelete = arg2.getBooleanExtra("isDelete", false);
			if (isDelete) {
				boolean f = cupboard().withDatabase(sqlDb).delete(
						CmdLoaclMessage.class,
						dataList.get(currentPosition)._id);
				if (f) {
					loadingData();
				}
			}

		}
	}
}
